/*
 * Copyright (C) 2004, Velocityme Partnership
 * GroupSessionBean.java
 *
 * Created on 26 July 2004, 06:55
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDeltaItemTypeBean;
import com.velocityme.entity.ChangeDeltaTypeBean;
import com.velocityme.entity.PermissionBean;
import javax.ejb.*;
import java.util.*;
import javax.naming.*;
import com.velocityme.interfaces.*;
import com.velocityme.utility.InvalidKeyException;
import com.velocityme.utility.PasswordEncrypter;
import com.velocityme.utility.PasswordIncorrectException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.valueobjects.*;
import java.rmi.RemoteException;

/**
 *
 * @author  Robert
 * @ejb.bean
 *           type="Stateless"
 *           cmp-version="2.x"
 *           name="GroupSession"
 *           jndi-name="ejb/GroupSession"
 *           view-type="local"
 *           transaction-type="Container"
 * @ejb.transaction type="Required"
 *
 * @ejb.util generate="physical"
 */
public class GroupSessionBean implements SessionBean {
    
    private SessionContext m_context;

    private SearchSessionLocal m_searchSessionLocal;
    
    private PermissionLocal m_permissionGroupCreate;
    private PermissionLocal m_permissionGroupEdit;
    private PermissionLocal m_permissionNodeView;

    /**
     * If the user has permission to create a new Group in the specified parent
     * node then go ahead and create it and log an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_parentNode The node which will contain the new User
     * @param p_groupValue The value details for the Group part of the group
     * @param p_usersLocal The collection of users assigned to the Group
     *
     * @ejb.interface-method view-type="local"
     **/
    public GroupLocal createGroup(KeySessionLocal p_keyLocal,
                                  NodeLocal p_parentNodeLocal,
                                  com.velocityme.valueobjects.GroupValue p_groupValue,
                                  java.util.Collection p_usersLocal)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, p_parentNodeLocal).contains(m_permissionGroupCreate)) {
                p_groupValue.getNodeValue().setType("Group");
                p_groupValue.getNodeValue().setFinalType("Group");
                DBObjectLocal dBObjectLocal = DBObjectUtil.getLocalHome().create();
                NodeValue nodeValue = p_groupValue.getNodeValue();
                NodeLocal nodeLocal = NodeUtil.getLocalHome().create(dBObjectLocal, nodeValue, p_parentNodeLocal);
                nodeValue.setNodeId(nodeLocal.getNodeId());
                GroupLocal groupLocal = GroupUtil.getLocalHome().create(nodeLocal, p_groupValue, p_usersLocal);
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.CREATE, p_keyLocal.getUserLocal(), dBObjectLocal);
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.PARENT_NODE, p_parentNodeLocal.getPathName());
                Iterator i = p_usersLocal.iterator();
                while(i.hasNext()) {
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.ADD_USER, ((UserLocal)i.next()).getPersonUserName());
                }
                return groupLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to edit the group then do so and log the
     * changes with an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_group The Group object being editted
     * @param p_groupValue The value details for the Group part of the group
     * @param p_usersLocal The collection of users assigned to the Group
     *
     * @ejb.interface-method view-type="local"
     **/
    public void editGroup(KeySessionLocal p_keyLocal,
                          GroupLocal p_groupLocal,
                          com.velocityme.valueobjects.GroupValue p_groupValue,
                          java.util.Collection p_usersLocal)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            NodeLocal nodeLocal = p_groupLocal.getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionGroupEdit)) {
                NodeValue nodeValue = p_groupValue.getNodeValue();
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.EDIT, p_keyLocal.getUserLocal(), nodeLocal.getDBObjectLocal());
                if (!nodeValue.getName().equals(nodeLocal.getName()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                if (!nodeValue.getDescription().equals(nodeLocal.getDescription()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                nodeLocal.setNodeValue(nodeValue);
                // check users
                Collection usersBefore = p_groupLocal.getUsersLocal();
                Collection usersRemoved = new ArrayList(usersBefore);
                Collection currentUsers = new ArrayList(p_usersLocal);
                usersRemoved.removeAll(currentUsers);
                Collection usersAdded = new ArrayList(currentUsers);
                usersAdded.removeAll(usersBefore);
                Iterator i = usersRemoved.iterator();
                while(i.hasNext()) {
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.REMOVE_USER, ((UserLocal)i.next()).getPersonUserName());
                }
                i = usersAdded.iterator();
                while(i.hasNext()) {
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.ADD_USER, ((UserLocal)i.next()).getPersonUserName());
                }
                p_groupLocal.setUsersLocal(p_usersLocal);
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to access a group then return the local object.
     *
     * @param p_key User's security key
     * @param p_groupPK The Department object to lookup
     *
     * @ejb.interface-method view-type="local"
     **/
    public GroupLocal getGroupLocal(KeySessionLocal p_keyLocal, 
                                    GroupPK p_groupPK)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            GroupLocal groupLocal = GroupUtil.getLocalHome().findByPrimaryKey(p_groupPK);
            NodeLocal nodeLocal = groupLocal.getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionNodeView)) {
                return groupLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * Get the full list of group value objects.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public java.util.Collection getAllValueObjects(KeySessionLocal p_keyLocal) throws InvalidKeyException {
        Collection values = new java.util.ArrayList();
        try {
            if (p_keyLocal.isValid()) {
                Collection users = GroupUtil.getLocalHome().findAll();
                Iterator i = users.iterator();
                while(i.hasNext()) {
                    GroupLocal groupLocal = (GroupLocal)i.next();
                    values.add(new GroupValueToString(groupLocal.getGroupValue()));
                }
            }
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return values;
    }
    
    /**
     * Create the Session Bean.
     * @throws CreateException 
     */
    public void ejbCreate() throws CreateException {
        try {
            m_searchSessionLocal = SearchSessionUtil.getLocalHome().create();
            m_permissionGroupCreate = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.GROUP_CREATE)));
            m_permissionGroupEdit = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.GROUP_EDIT)));
            m_permissionNodeView = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.NODE_VIEW)));
        }
        catch(NamingException e) {
            throw new CreateException(e.getMessage());
        }
        catch(FinderException e) {
            throw new CreateException(e.getMessage());
        }
    }

    public void ejbActivate() throws java.rmi.RemoteException {
    }
    
    public void ejbPassivate() throws java.rmi.RemoteException {
    }
    
    public void ejbRemove() throws java.rmi.RemoteException {
    }
    
    public void setSessionContext(javax.ejb.SessionContext sessionContext) throws java.rmi.RemoteException {
        m_context = sessionContext;
    }
    
}
